import React, { useState, useEffect, useContext } from "react";
import Header from "../../components/Header/Header";
import { $pre } from "../../http/http";
import "./Shop.less";
import yImg from "../../assets/img/y.jpeg";
import nImg from "../../assets/img/n.jpeg";
import { Button, SwipeAction, Dialog, Toast } from "antd-mobile";
import { filterPrice } from "../../filters";
import { reqcartdelete, reqcartedit, reqcartlist } from "../../http/api";
import { MyContext } from "../../App";

const Shop = (props) => {
  const [arr, setArr] = useState([])
  const [allChecked, setAllChecked] = useState(false)
  const [isRequest, setIsRequest] = useState(true)
  const { state: { info: { uid } } } = useContext(MyContext)

  useEffect(() => {
    reqList()
  }, [])
  const reqList = () => {
    reqcartlist({ uid }).then(res => {
      if (res.data.code === 200) {
        let list = res.data.list[1].content ? res.data.list[1].content : []
        list.forEach(item => {
          let obj = arr.find(i => i.id === item.id)
          item.checked = obj ? obj.checked : false
        })
        setArr([...list])
        setAllChecked(list.length > 0 ? list.every(item => item.checked) : false)
        setIsRequest(true)
      }
    })
  }

  const add = id => {
    reqcartedit({ id, type: 2 }).then(res => {
      if (res.data.code === 200) {
        Toast.show({
          content: res.data.msg
        })
        reqList()
      }
    })
  }
  const sub = (id, num) => {
    if (num > 1 && isRequest) {
      setIsRequest(false)
      reqcartedit({ id, type: 1 }).then(res => {
        if (res.data.code === 200) {
          Toast.show({
            content: res.data.msg
          })
          reqList()
        }
      })
    } else {
      Toast.show({
        content: "宝贝不能再少了"
      })
    }
  }
  const del = id => {
    reqcartdelete({ id }).then(res => {
      if (res.data.code === 200) {
        Toast.show({
          content: res.data.msg
        })
        reqList()
      }
    })
  }
  const changeAll = () => {
    let a = !allChecked
    setAllChecked(a)
    arr.forEach(item => {
      item.checked = a
    })
    setArr(arr)
  }
  const changeOne = index => {
    arr[index].checked = !arr[index].checked
    setArr([...arr])
    setAllChecked(arr.every(item => item.checked))
  }
  
  const allPrice = arr.reduce(
    (v, i) => (i.checked ? v + i.price * i.num : v),
    0
  )
  return (
    <div>
      <Header title="购物车" back></Header>
      {arr.map((item, index) => (
        <SwipeAction
          key={item.id}
          closeOnAction={false}
          closeOnTouchOutside={false}
          rightActions={[
            {
              key: "delete",
              text: "删除",
              color: "danger",
              onClick: async () => {
                await Dialog.confirm({
                  content: "确定要删除吗？",
                  onConfirm: () => {
                    del(item.id);
                  },
                });
              },
            },
          ]}
        >
          <div className="item">
            <img
              className="checkbox"
              src={item.checked ? yImg : nImg}
              alt=""
            />
            <img
              onClick={() => changeOne(index)}
              className="img"
              src={$pre + item.img}
              alt=""
            />
            <div className="right">
              <h3>{item.goodsname}</h3>
              <div>￥{filterPrice(item.price)}</div>
              <div>
                <Button onClick={() => sub(item.id, item.num)}>-</Button>
                {item.num}
                <Button onClick={() => add(item.id)}>+</Button>
              </div>
            </div>
          </div>
        </SwipeAction>
      ))}

      {/* 全选总价 */}
      <div className="footer">
        <div className="allChecked" onClick={() => changeAll()}>
          <img className="checkbox" src={allChecked ? yImg : nImg} alt="" />
          全选
        </div>
        <div className="allPrice"><span>总计:</span>￥{filterPrice(allPrice)}</div>
        <Button shape='default' color="warning" onClick={() => props.history.push("/order")}>结算</Button>
      </div>
    </div>
  )
}


export default Shop